<!-- 用户管理 -->
<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import { getConfigPage, deleteConfig, saveConfig } from "@/api/config";
import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/role";

import { ConfigForm, ConfigQuery, ConfigPageVO } from "@/api/config/types";
import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";
import Editor from "@/components/WangEditor/index.vue";

const value = ref("初始内容");

const queryFormRef = ref(ElForm); // 查询表单
const ConfigFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<ConfigQuery>({
  pageNum: 1,
  pageSize: 10,
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<ConfigPageVO[]>(); // 用户分页数据
const deptList = ref<OptionType[]>(); // 部门下拉数据源
const roleList = ref<OptionType[]>(); // 角色下拉数据源

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: "50%",
  title: "",
});

// 用户表单数据
const formData = reactive<ConfigForm>({
  configType: "",
  configValue: "",
  configId: "",
  configTxt: "",
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getConfigPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.type = undefined;
  queryParams.startTime = "";
  queryParams.endTime = "";
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.configId);
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(type: string, row?: any) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    if (row != undefined && row.configId) {
      dialog.title = "修改配置";
      Object.assign(formData, { ...row });
    } else {
      formData.configId = "";
      formData.configType = "";
      formData.configValue = "";
      formData.configTxt = "";
      dialog.title = "新增配置";
    }
  } else if (dialog.type === "user-import") {
    dialog.width = "500px";
    loadDeptOptions();
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    ConfigFormRef.value.resetFields();
    ConfigFormRef.value.clearValidate();
    formData.configId = undefined;
  } else if (dialog.type === "user-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  ConfigFormRef.value.validate((valid: any) => {
    if (valid) {
      const configId = formData.configId;
      loading.value = true;
      if (configId) {
        saveConfig(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        saveConfig(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteConfig(userIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

// /** 下载导入模板 */
// function downloadTemplate() {
//   downloadTemplateApi().then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

/** Excel文件 Change */
function handleFileChange(file: any) {
  importData.file = file.raw;
}

/** Excel文件 Exceed  */
function handleFileExceed(files: any) {
  uploadRef.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value!.handleStart(file);
  importData.file = file;
}

/** 导出用户 */
// function handleExport() {
//   exportUser(queryParams).then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
// }

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="类型" prop="configType">
              <el-select
                v-model="queryParams.configType"
                placeholder="全部"
                clearable
                class="!w-[100px]"
              >
                <el-option label="普通用户" value="1" />
                <el-option label="认证用户" value="2" />
                <el-option label="VIP用户" value="3" />
                <el-option label="会员价格" value="5" />
                <el-option label="加塞价格" value="6" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['sys:user:add']"
                  type="success"
                  @click="openDialog('user-form')"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              align="center"
              label="序号"
              type="index"
              width="150"
            />
            <el-table-column
              key="username"
              label="配置类型"
              align="center"
              prop="type"
            >
              <template #default="scope">
                <span v-if="scope.row.configType == 1">普通用户</span>
                <span v-if="scope.row.configType == 2">认证用户</span>
                <span v-if="scope.row.configType == 3">VIP用户</span>
                <span v-if="scope.row.configType == 5">会员价格</span>
                <span v-if="scope.row.configType == 6">加塞价格</span>
              </template>
            </el-table-column>

            <el-table-column label="有效值" align="center" prop="configValue" />
            <el-table-column label="描述" align="center" prop="configTxt" />
            <el-table-column label="操作" align="center" prop="status">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  ><i-ep-edit />修改</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      height="90%"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="ConfigFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="配置类型" prop="configType">
          <el-select v-model="formData.configType" placeholder="请选择">
            <el-option label="普通用户" value="1" />
            <el-option label="认证用户" value="2" />
            <el-option label="VIP用户" value="3" />
            <el-option label="会员价格" value="5" />
            <el-option label="加塞价格" value="6" />
          </el-select>
        </el-form-item>

        <el-form-item label="配置项值">
          <el-input v-model="formData.configValue" placeholder="请输入有效值" />
        </el-form-item>

        <el-form-item label="配置描述">
          <el-input v-model="formData.configTxt" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
